from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from .models import Employee

@receiver(post_save, sender=User)
def create_or_update_employee(sender, instance, created, **kwargs):
    # if created is True, create a new employee, otherwise update it
    if created:
        employee_obj = Employee.objects.create(
            email=instance.email,
            name=instance.last_name.strip()+instance.first_name.strip(),
            is_valid=False,
            user=instance,
        )
    else:
        # if created is False, and failed to find employee, do nonthing, 
        # otherwise update the employee's email
        try: 
            employee_obj = Employee.objects.get(user=instance)
        except Employee.DoesNotExist:
            print(f"Employee does not exist for user {instance.username}")
            return 
        fullname = instance.last_name.strip()+instance.first_name.strip()
        if employee_obj.email != instance.email or employee_obj.name != fullname:
            employee_obj.email = instance.email
            employee_obj.name = fullname
            employee_obj.save()
